import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/calendar_event.dart';
import '../models/dateline_event.dart';
import '../providers/dateline_providers.dart';

/// 混合事件列表组件，同时显示日历事件和时间线事件
class MixedEventList extends ConsumerWidget {
  /// 要显示的日历事件列表
  final List<CalendarEvent> calendarEvents;
  /// 选中的日期
  final DateTime selectedDate;
  /// 点击日历事件的回调函数
  final Function(CalendarEvent) onCalendarEventTap;
  /// 空状态消息
  final String emptyStateMessage;

  /// 构造函数
  const MixedEventList({
    Key? key,
    required this.calendarEvents,
    required this.selectedDate,
    required this.onCalendarEventTap,
    this.emptyStateMessage = '没有事件',
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 获取选中日期的时间线事件
    final datelineEvents = ref.watch(selectedDateDatelineEventsProvider(selectedDate));

    // 合并所有事件并按时间排序
    final allEvents = <dynamic>[];
    allEvents.addAll(calendarEvents);
    allEvents.addAll(datelineEvents);

    // 如果没有事件，显示空状态
    if (allEvents.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.event_busy,
              size: 64,
              color: Colors.grey,
            ),
            const SizedBox(height: 16),
            Text(
              emptyStateMessage,
              style: const TextStyle(color: Colors.grey),
            ),
          ],
        ),
      );
    }

    // 按时间排序事件
    allEvents.sort((a, b) {
      DateTime timeA;
      DateTime timeB;
      
      if (a is CalendarEvent) {
        timeA = a.startTime;
      } else if (a is DatelineEvent) {
        timeA = a.eventTime;
      } else {
        timeA = DateTime.now();
      }
      
      if (b is CalendarEvent) {
        timeB = b.startTime;
      } else if (b is DatelineEvent) {
        timeB = b.eventTime;
      } else {
        timeB = DateTime.now();
      }
      
      return timeA.compareTo(timeB);
    });

    return ListView.builder(
      padding: const EdgeInsets.all(8),
      itemCount: allEvents.length,
      itemBuilder: (context, index) {
        final event = allEvents[index];
        if (event is CalendarEvent) {
          return _buildCalendarEventCard(context, event);
        } else if (event is DatelineEvent) {
          return _buildDatelineEventCard(context, event);
        }
        return const SizedBox.shrink();
      },
    );
  }

  /// 构建日历事件卡片
  Widget _buildCalendarEventCard(BuildContext context, CalendarEvent event) {
    return Card(
      elevation: 2,
      margin: const EdgeInsets.symmetric(vertical: 8),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () => onCalendarEventTap(event),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 事件类型图标
              CircleAvatar(
                backgroundColor: event.eventType.color,
                child: IconTheme(
                  data: const IconThemeData(color: Colors.white),
                  child: event.eventType.icon,
                ),
              ),
              const SizedBox(width: 16),
              // 事件详情
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            event.title,
                            style: Theme.of(context).textTheme.titleMedium,
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                          decoration: BoxDecoration(
                            color: Colors.blue.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Text(
                            '日历',
                            style: Theme.of(context).textTheme.bodySmall?.copyWith(
                              color: Colors.blue,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      event.description ?? '',
                      style: Theme.of(context).textTheme.bodyMedium,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 8),
                    // 事件时间和地点信息
                    Row(
                      children: [
                        const Icon(
                          Icons.access_time,
                          size: 16,
                          color: Colors.grey,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          _formatCalendarEventTime(event),
                          style: Theme.of(context).textTheme.bodySmall,
                        ),
                        if (event.location != null) ...[  
                          const SizedBox(width: 16),
                          const Icon(
                            Icons.location_on,
                            size: 16,
                            color: Colors.grey,
                          ),
                          const SizedBox(width: 4),
                          Expanded(
                            child: Text(
                              event.location!,
                              style: Theme.of(context).textTheme.bodySmall,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建时间线事件卡片
  Widget _buildDatelineEventCard(BuildContext context, DatelineEvent event) {
    return Card(
      elevation: 2,
      margin: const EdgeInsets.symmetric(vertical: 8),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () => _showDatelineEventDetails(context, event),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 事件类型图标
              CircleAvatar(
                backgroundColor: event.eventType.color,
                child: IconTheme(
                  data: const IconThemeData(color: Colors.white),
                  child: event.eventType.icon,
                ),
              ),
              const SizedBox(width: 16),
              // 事件详情
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            event.title,
                            style: Theme.of(context).textTheme.titleMedium,
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                          decoration: BoxDecoration(
                            color: Colors.orange.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Text(
                            '时间线',
                            style: Theme.of(context).textTheme.bodySmall?.copyWith(
                              color: Colors.orange,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      event.description ?? '',
                      style: Theme.of(context).textTheme.bodyMedium,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 8),
                    // 事件时间信息
                    Row(
                      children: [
                        const Icon(
                          Icons.access_time,
                          size: 16,
                          color: Colors.grey,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          _formatDatelineEventTime(event.eventTime),
                          style: Theme.of(context).textTheme.bodySmall,
                        ),
                      ],
                    ),
                    // 显示照片数量
                    if (event.photoUrls.isNotEmpty) ...[
                      const SizedBox(height: 4),
                      Row(
                        children: [
                          const Icon(
                            Icons.photo,
                            size: 16,
                            color: Colors.grey,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            '${event.photoUrls.length} 张照片',
                            style: Theme.of(context).textTheme.bodySmall,
                          ),
                        ],
                      ),
                    ],
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 显示时间线事件详情
  void _showDatelineEventDetails(BuildContext context, DatelineEvent event) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  CircleAvatar(
                    backgroundColor: event.eventType.color,
                    child: IconTheme(
                      data: const IconThemeData(color: Colors.white),
                      child: event.eventType.icon,
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Text(
                      event.title,
                      style: Theme.of(context).textTheme.titleLarge,
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.orange.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Text(
                      '时间线事件',
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Colors.orange,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              Text(
                event.description ?? '',
                style: Theme.of(context).textTheme.bodyLarge,
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  const Icon(Icons.access_time, color: Colors.grey),
                  const SizedBox(width: 8),
                  Text(
                    _formatDatelineEventTime(event.eventTime),
                    style: Theme.of(context).textTheme.bodyMedium,
                  ),
                ],
              ),
              if (event.photoUrls.isNotEmpty) ...[
                const SizedBox(height: 16),
                Text(
                  '照片 (${event.photoUrls.length})',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                const SizedBox(height: 8),
                SizedBox(
                  height: 100,
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: event.photoUrls.length,
                    itemBuilder: (context, index) {
                      return Container(
                        margin: const EdgeInsets.only(right: 8),
                        width: 100,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          image: DecorationImage(
                            image: NetworkImage(event.photoUrls[index]),
                            fit: BoxFit.cover,
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ],
              const SizedBox(height: 16),
            ],
          ),
        );
      },
    );
  }

  /// 格式化日历事件时间
  String _formatCalendarEventTime(CalendarEvent event) {
    if (event.isAllDay) {
      return '全天';
    }
    
    final startTime = '${event.startTime.hour.toString().padLeft(2, '0')}:${event.startTime.minute.toString().padLeft(2, '0')}';
    
    if (event.endTime != null) {
      final endTime = '${event.endTime!.hour.toString().padLeft(2, '0')}:${event.endTime!.minute.toString().padLeft(2, '0')}';
      return '$startTime - $endTime';
    }
    
    return startTime;
  }

  /// 格式化时间线事件时间
  String _formatDatelineEventTime(DateTime dateTime) {
    return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}